<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\User;

use App\Dao\CartDao;
use App\Dao\GoodsSkuDao;
use App\Service\Service;

use Hyperf\Di\Annotation\Inject;

/**
 * 购物车服务
 *
 * @author 谢声强(861167322@qq.com)
 * @package App\Service\User
 */
class CartService  extends Service
{
    /**
     * 商品SKU DAO
     *
     * @Inject
     * @var GoodsSkuDao
     */
    public $sku_dao;

    /**
     * 购物车 DAO
     *
     * @Inject
     * @var CartDao
     */
    public $dao;

    /**
     * 添加商品 SKU 到购物车
     *
     * @param int $sku_id
     * @param int $num
     * @return mixed
     */
    public function add(int $sku_id, int $num)
    {
        $sku = $this->sku_dao->first(['id' => $sku_id]);

        // 库存不足
        if ($sku->stock < $num) {
            $this->error('CART.SKU_STOCK_NOT_ENOUGH');
        }

        // 只有现金商品能加入购物车
        if ($sku->goods->buy_type !== 0) {
            $this->error('CART.BUY_TYPE_FAIL');
        }

        // 商品禁用也不能加入购物车
        if ($sku->goods->disable !== 1) {
            $this->error('CART.GOODS_DISABLE');
        }

        // 已存在购物车，数量直接更新
        if ($cart = $this->dao->getCartBySkuId($sku->id)) {
            $cart->num += $num;
            return $cart->save();
        }

        return $this->dao->create([
            'user_id' => uid(),
            'goods_id' => $sku->goods_id,
            'num' => $num,
            'joined_price' => $sku->price,
            'sku_id' => $sku->id
        ]);
    }
}